package com.wpre.vampiremq.mqserver;

import com.wpre.vampiremq.common.*;
import com.wpre.vampiremq.mqserver.core.BasicProperties;

import javax.xml.crypto.Data;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:消息队列中的本体服务器,是一个TCP服务器
 * User: LianBao
 * Date: 2025-01-19
 * Time: 15:37
 */
public class BrokerServer {
    private ServerSocket serverSocket = null;
    //单个虚拟主机
    private VirtualHost virtualHost = new VirtualHost("default");
    //表示当前所有会话,key是channelId,value是对应的Socket对象
    private ConcurrentHashMap<String, Socket> session = new ConcurrentHashMap<String, Socket>();
    //线程池,处理多个客户端的请求
    private ExecutorService executorService = null;
    //服务器是否继续运行
    private volatile boolean runnable = true;
    public BrokerServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    //启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动");
        executorService = Executors.newCachedThreadPool();
        try {
            while (runnable) {
                Socket clientSocket = serverSocket.accept();
                //把处理连接的逻辑丢给线程池
                executorService.submit(() -> {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                });
            }
        } catch (SocketException e) {
            System.out.println("BrokerServer停止运行!");
        }
    }
    //这个方法,用于处理一个客户端的连接
    private void processConnection(Socket clientSocket) throws IOException, ClassNotFoundException {
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()) {
            //
            try (DataInputStream dataInputStream = new DataInputStream(inputStream);
                 DataOutputStream dataOutputStream = new DataOutputStream(outputStream);) {
                while (true) {
                    //1.读取请求并且解析
                    Request request = readRequest(dataInputStream);
                    //2.根据请求计算响应
                    Response response = process(request, clientSocket);
                    //3.把响应写回客户端
                    writeResponse(dataOutputStream, response);


                }
            } catch (EOFException | SocketException exception) {
                System.out.println("connection 关闭");
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭Socket
            clientSocket.close();
            //把当前Socket中对应的所有channel都清理
            clearClosedSession(clientSocket);

        }
    }
    //清理channel
    private void clearClosedSession(Socket clientSocket) {
        List<String> toDel = new ArrayList<>();
        for (Map.Entry<String, Socket> entry : session.entrySet()) {
            if (entry.getValue() == clientSocket) {
                //这里,不能直接删除,集合类不能一边遍历,一边删除,而是把要删除的结果保存
                toDel.add(entry.getKey());
            }
        }
        for (String channelId : toDel) {
            session.remove(channelId);
        }

    }
    //响应写回客户端
    private void writeResponse(DataOutputStream dataOutputStream, Response response) throws IOException {
        dataOutputStream.writeInt(response.getType());
        dataOutputStream.writeInt(response.getLength());
        dataOutputStream.write(response.getPayload());
        //写完之后刷新缓冲区
        dataOutputStream.flush();
    }
    //根据请求计算响应
    private Response process(Request request, Socket clientSocket) throws IOException, ClassNotFoundException {
        //1.把request中的payload进行解析
        BasicArguments basicArguments = (BasicArguments) BinaryTool.fromBytes(request.getPayload());
        //2.根据type,区分请求要干啥
        boolean ok = true;
        if (request.getType() == 0x1) {
            //创建channel
            session.put(basicArguments.getChannelId(), clientSocket);
        } else if (request.getType() == 0x2) {
            //关闭channel
            session.remove(basicArguments.getChannelId());
        } else if (request.getType() == 0x3) {
            //创建交换机
            ExchangeDeclareArguments arguments = (ExchangeDeclareArguments) basicArguments;
            ok = virtualHost.exchangeDeclare(
                    arguments.getExchangeName(),
                    arguments.getExchangeType(),
                    arguments.isDurable(),
                    arguments.isAutoDelete(),
                    arguments.getArguments());
        } else if (request.getType() == 0x4) {
            //销毁交换机
            ExchangeDeleteArguments arguments = (ExchangeDeleteArguments) basicArguments;
            ok = virtualHost.exchangeDelete(arguments.getExchangeName());

        } else if (request.getType() == 0x5) {
            //创建队列
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDeclare(arguments.getQueueName(),
                    arguments.isDurable(),
                    arguments.isExclusive(),
                    arguments.isAutoDelete(),
                    arguments.getArguments());
        } else if (request.getType() == 0x6) {
            //销毁队列
            QueueDeclareArguments arguments = (QueueDeclareArguments) basicArguments;
            ok = virtualHost.queueDelete(arguments.getQueueName());
        } else if (request.getType() == 0x7) {
            //创建绑定
            QueueBindArguments arguments = (QueueBindArguments) basicArguments;
            ok = virtualHost.queueBind(arguments.getQueueName(), arguments.getExchangeName(), arguments.getBindingKey());
        } else if (request.getType() == 0x8) {
            //销毁绑定
            QueueUnbindArguments arguments = (QueueUnbindArguments) basicArguments;
            ok = virtualHost.queueUnbind(arguments.getQueueName(), arguments.getExchangeName());
        } else if (request.getType() == 0x9) {
            //发送消息
            BasicPublishArguments arguments = (BasicPublishArguments) basicArguments;
            ok = virtualHost.basicPublish(arguments.getExchangeName(), arguments.getRoutingKey(), arguments.getBasicProperties(), arguments.getBody());
        } else if (request.getType() == 0xa) {
            //订阅message
            BasicConsumeArguments arguments = (BasicConsumeArguments) basicArguments;
            ok = virtualHost.basicConsume(arguments.getConsumerTag(), arguments.getQueueName(), arguments.isAutoAck(), new Consumer() {
                //回调函数
                @Override
                public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws IOException {
                    //这个回调函数的作用是把服务器收到的信息可以直接推送给对应的消费者消费,consumerTag相当于channelId,根据channelId去session中查询,就能得到对应的Socket对象

                    //1.根据channelId找到Socket对象
                    Socket clientSocket = session.get(consumerTag);
                    if (clientSocket == null || clientSocket.isClosed()) {
                        throw new MQException("订阅消息的客户端已经关闭");
                    }
                    //2.构造响应数据
                    Response response = new Response();
                    response.setType(0xc);//服务器给消费者客户端推送的消息数据
                    //Response的payload是一个subscribeReturns
                    SubscribeReturns subscribeReturns = new SubscribeReturns();
                    subscribeReturns.setConsumerTag(consumerTag);
                    subscribeReturns.setBasicProperties(basicProperties);
                    subscribeReturns.setBody(body);
                    subscribeReturns.setRid("");//服务器给消费者客户端推送的消息数据,没有请求,不设置也可以
                    subscribeReturns.setOk(true);
                    subscribeReturns.setChannelId(consumerTag);
                    byte[] payload = BinaryTool.toBytes(subscribeReturns);
                    response.setLength(payload.length);
                    response.setPayload(payload);
                    //把数据写回到客户端,此处的DataOutputStream不能close,如果关闭了,clientSocket里的OutputStream也会关闭
                    //因为是源源不断的鞋数据
                    DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
                    writeResponse(dataOutputStream, response);
                }
            });
        } else if (request.getType() == 0xb) {
            //调用basicAck,确认消息
            BasicAckArguments arguments = (BasicAckArguments) basicArguments;
            ok = virtualHost.basicAck(arguments.getQueueName(), arguments.getMessageId());
        } else {
            //当前type非法
            throw new MQException("未知的type" + request.getType());
        }
        //3.构造响应
        BasicReturns basicReturns = new BasicReturns();
        basicReturns.setRid(basicArguments.getRid());
        basicReturns.setOk(true);
        basicReturns.setChannelId(basicArguments.getChannelId());

        byte[] payload = BinaryTool.toBytes(basicReturns);
        Response response = new Response();
        response.setType(request.getType());
        response.setLength(payload.length);
        response.setPayload(payload);

        return response;
    }
    //读取请求
    private Request readRequest(DataInputStream dataInputStream) throws IOException {
        Request request = new Request();
        request.setType(dataInputStream.readInt());

        request.setLength(dataInputStream.readInt());

        byte[] payload = new byte[request.getLength()];
        int n = dataInputStream.read(payload);
        if (n != request.getLength()) {
            throw new IOException("读取格式错误");
        }
        //读取到之后设置
        request.setPayload(payload);

        return request;
    }
    //停止服务器(用于单元测试)
    public void stop() throws IOException {
        runnable = false;
        //停止线程池
        executorService.shutdownNow();
        serverSocket.close();

    }
}
